import utils from "./utils";
export default {
  onDrawn(drawnFn) {
    if (!drawnFn || typeof drawnFn != "function") drawnFn = function() {};
    this.drawnFn = drawnFn;
  },
  onMousedown(opt, canvas) {
    var drawObj = {
      id: new Date().getTime() + "_obj",
    };
    drawObj.isDrawing = true;
    drawObj.drawType = "Rect";
    drawObj.pointers = [
      {
        y: opt.absolutePointer.y,
        x: opt.absolutePointer.x,
      },
      {
        y: opt.absolutePointer.y,
        x: opt.absolutePointer.x,
      },
    ];
    this.drawObj = drawObj;
    this.draw(canvas, this.drawObj);
  },
  onMousemove(opt, canvas) {
    if (!this.drawObj || !this.drawObj.isDrawing) return;
    this.drawObj.pointers[1].x = opt.absolutePointer.x;
    this.drawObj.pointers[1].y = opt.absolutePointer.y;

    this.draw(canvas, this.drawObj);
  },
  onMouseup(opt, canvas) {
    this.drawObj.isDrawing = false;

    let width = this.drawObj.pointers[1].x - this.drawObj.pointers[0].x;
    let height = this.drawObj.pointers[1].y - this.drawObj.pointers[0].y;

    let top = this.drawObj.pointers[0].y;
    let left = this.drawObj.pointers[0].x;

    if (width < 0) {
      left = this.drawObj.pointers[1].x;
    }

    if (height < 0) {
      top = this.drawObj.pointers[1].y;
    }

    this.drawObj.pointers[0].x = left;
    this.drawObj.pointers[0].y = top;
    this.drawObj.pointers[1].x = left+Math.abs(width);
    this.drawObj.pointers[1].y = top+Math.abs(height);


    if (this.drawnFn) this.drawnFn(this.drawObj);
  },
  draw(canvas, drawObj) {
    let width = drawObj.pointers[1].x - drawObj.pointers[0].x;
    let height = drawObj.pointers[1].y - drawObj.pointers[0].y;

    let top = drawObj.pointers[0].y;
    let left = drawObj.pointers[0].x;

    if (width < 0) {
      left = drawObj.pointers[1].x;
    }

    if (height < 0) {
      top = drawObj.pointers[1].y;
    }
    var drawOptions ={}
    if (drawObj.fabricObj) {
      drawOptions ={
        top: top,
        left: left,
        width: Math.abs(width),
        height: Math.abs(height),
        strokeWidth: 3 / canvas.getZoom(),
      }
      drawObj.fabricObj.set(utils.combineOptions(drawOptions,drawObj.drawOptions));
      canvas.requestRenderAll();
    } else {
      drawOptions ={
        top: top,
        left: left,
        width: Math.abs(width),
        height: Math.abs(height),
        fill: "rgb(0,0,0,0)",
        strokeWidth: 3 / canvas.getZoom(),
        stroke: "red",
        selectable: false,
        lockMovementY:true,
      }
      drawObj.fabricObj = new fabric.Rect(utils.combineOptions(drawOptions,drawObj.drawOptions));
      canvas.add(drawObj.fabricObj);
    }
    drawOptions=null;
  },
  remove(canvas, drawObj) {
    if (drawObj.fabricObj) {
      canvas.remove(drawObj.fabricObj);
      //drawObj.fabricObj.dispose();
      drawObj.fabricObj = null;
    }
  },
};
